<template>
  <section>
    <div class="box">
      <div class="container">
        <h2 class="page-title">贷款管理</h2>
        
        <!-- 贷款申请表单 -->
        <el-form 
          :model="loanForm" 
          :rules="rules"
          ref="loanFormRef"
          label-width="120px"
          class="loan-form"
        >
          <el-form-item label="贷款金额" prop="amount">
            <el-input-number 
              v-model="loanForm.amount" 
              :min="1000"
              :max="1000000"
              :step="1000"
              placeholder="请输入贷款金额"
              class="full-width"
            />
          </el-form-item>
          
          <el-form-item label="贷款期限" prop="term">
            <el-select v-model="loanForm.term" placeholder="请选择贷款期限" class="full-width">
              <el-option label="3个月" value="3" />
              <el-option label="6个月" value="6" />
              <el-option label="12个月" value="12" />
              <el-option label="24个月" value="24" />
              <el-option label="36个月" value="36" />
              <el-option label="48个月" value="48" />
              <el-option label="60个月" value="60" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="贷款用途" prop="purpose">
            <el-input 
              v-model="loanForm.purpose"
              type="textarea"
              placeholder="请简要说明贷款用途"
              :rows="2"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitLoanApplication" :loading="loading">
              申请贷款
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 贷款列表 -->
        <div class="loan-list">
          <h3>贷款列表</h3>
          <el-table 
            :data="loanList" 
            style="width: 100%"
            :stripe="true"
            :border="true"
          >
            <el-table-column prop="loanId" label="贷款编号" width="120" />
            <el-table-column prop="customerId" label="用户ID" width="120" />
            <el-table-column prop="amount" label="贷款金额">
              <template #default="scope">
                ¥{{ formatMoney(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="issueDate" label="贷款日期">
              <template #default="scope">
                {{ formatDate(scope.row.issueDate) }}
              </template>
            </el-table-column>
            <el-table-column prop="loanStatus" label="状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.loanStatus)">
                  {{ scope.row.loanStatus }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button
                  v-if="scope.row.loanStatus === '未还'"
                  type="primary" 
                  size="small" 
                  @click="showRepaymentDialog(scope.row)"
                >
                  还款
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="showLoanDetail(scope.row.loanId)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 贷款详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="贷款详情"
      width="500px"
      destroy-on-close
    >
      <div v-if="selectedLoan" class="loan-detail">
        <div class="detail-item">
          <span class="label">贷款编号：</span>
          <span>{{ selectedLoan.loanId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">用户ID：</span>
          <span>{{ selectedLoan.customerId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">贷款金额：</span>
          <span>¥{{ formatMoney(selectedLoan.amount) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">贷款日期：</span>
          <span>{{ formatDate(selectedLoan.issueDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">贷款状态：</span>
          <el-tag :type="getStatusType(selectedLoan.loanStatus)">
            {{ selectedLoan.loanStatus }}
          </el-tag>
        </div>
      </div>
    </el-dialog>

    <!-- 还款对话框 -->
    <el-dialog
      v-model="repaymentDialogVisible"
      title="贷款还款"
      width="500px"
      destroy-on-close
    >
      <div v-if="selectedLoan" class="repayment-form">
        <div class="loan-info">
          <div class="info-item">
            <span class="label">贷款编号：</span>
            <span>{{ selectedLoan.loanId }}</span>
          </div>
          <div class="info-item">
            <span class="label">贷款总额：</span>
            <span>¥{{ formatMoney(selectedLoan.amount) }}</span>
          </div>
          <div class="info-item">
            <span class="label">贷款日期：</span>
            <span>{{ formatDate(selectedLoan.issueDate) }}</span>
          </div>
        </div>

        <el-form 
          :model="repaymentForm"
          :rules="repaymentRules"
          ref="repaymentFormRef"
          label-width="100px"
          class="repayment-input"
        >
          <el-form-item label="还款金额" prop="amount">
            <el-input-number
              v-model="repaymentForm.amount"
              :min="1"
              :max="Number(selectedLoan.amount)"
              :precision="2"
              :step="100"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>

        <div class="dialog-footer">
          <el-button @click="repaymentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRepayment" :loading="loading">
            确认还款
          </el-button>
        </div>
      </div>
    </el-dialog>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 表单数据
const loanFormRef = ref(null)
const loanForm = ref({
  amount: '',
  term: '',
  purpose: '',
  userId: '', // 需要从登录用户信息中获取
  loanStatus: 'PENDING'
})

// 表单验证规则
const rules = {
  amount: [
    { required: true, message: '请输入贷款金额', trigger: 'blur' },
    { type: 'number', min: 1000, max: 1000000, message: '贷款金额必须在1000-1000000之间', trigger: 'blur' }
  ],
  term: [
    { required: true, message: '请选择贷款期限', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请输入贷款用途', trigger: 'blur' },
    { min: 10, max: 200, message: '贷款用途描述需在10-200字之间', trigger: 'blur' }
  ]
}

// 状态管理
const loading = ref(false)
const loans = ref([])
const statusFilter = ref('')
const detailDialogVisible = ref(false)
const repaymentDialogVisible = ref(false)
const selectedLoan = ref(null)
const repaymentSchedule = ref([])
const loanList = ref([])
const repaymentFormRef = ref(null)

// 还款表单数据
const repaymentForm = reactive({
  amount: 0
})

// 还款表单验证规则
const repaymentRules = {
  amount: [
    { required: true, message: '请输入还款金额', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入还款金额'))
        } else if (value <= 0) {
          callback(new Error('还款金额必须大于0'))
        } else if (selectedLoan.value && value > Number(selectedLoan.value.amount)) {
          callback(new Error('还款金额不能超过贷款总额'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性：过滤后的贷款列表
const filteredLoans = computed(() => {
  if (!statusFilter.value) return loans.value
  return loans.value.filter(loan => loan.status === statusFilter.value)
})

// 页面加载时获取贷款列表
onMounted(async () => {
  await fetchLoanList()
})

// 获取贷款列表
async function fetchLoanList() {
  try {
    loading.value = true
    // 假设当前用户ID为1，实际应该从登录信息获取
    const userId = '1'
    const response = await request.get(`/loan/status/${userId}`)
    //alert(response.data.code)
    if (response.data.code === 0) {
      loanList.value = response.data.data;
      //alert(loanList.value[0].loanId)
    } else {
      ElMessage.error(response.message || '获取贷款列表失败')
    }
  } catch (error) {
    console.error('获取贷款列表失败:', error)
    ElMessage.error('获取贷款列表失败')
  } finally {
    loading.value = false
  }
}

// 提交贷款申请
async function submitLoanApplication() {
  if (!loanFormRef.value) return
  
  try {
    await loanFormRef.value.validate()
    loading.value = true
    
    const response = await request.post('/loan/apply', {
      userId: loanForm.value.userId,
      amount: loanForm.value.amount,
      term: parseInt(loanForm.value.term),
      purpose: loanForm.value.purpose,
      loanStatus: 'PENDING',
      applyDate: new Date().toISOString()
    })
    
    if (response.data.code === 0) {
      ElMessage.success('贷款申请提交成功')
      loanFormRef.value.resetFields()
      await fetchLoanList() // 刷新列表
    } else {
      ElMessage.error(response.data.message || '贷款申请失败')
    }
  } catch (error) {
    console.error('贷款申请失败:', error)
    ElMessage.error('贷款申请失败')
  } finally {
    loading.value = false
  }
}

// 显示还款对话框
const showRepaymentDialog = (loan) => {
  selectedLoan.value = loan
  repaymentForm.amount = Number(loan.amount) // 默认填入贷款总额
  repaymentDialogVisible.value = true
}

// 处理还款
const handleRepayment = async () => {
  if (!repaymentFormRef.value) return

  try {
    await repaymentFormRef.value.validate()
    
    // 二次确认
    

    loading.value = true
    
    // 构造还款请求数据
    const repaymentData = {
      loanId: selectedLoan.value.loanId,  // 添加贷款ID
      amount: repaymentForm.amount        // 还款金额
    }
    
    // 发送还款请求
    const response = await request.post('/loan/payment', repaymentData)  // 修改为直接传入包含ID和金额的对象

    if (response.data.code === 0) {
      ElMessage.success('还款成功')
      repaymentDialogVisible.value = false
      await fetchLoanList() // 刷新列表
    } else {
      ElMessage.error(response.data.message || '还款失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('还款失败:', error)
    ElMessage.error('还款失败')
  } finally {
    loading.value = false
  }
}

// 显示贷款详情
function showLoanDetail(loanId) {
  const loan = loanList.value.find(item => item.loanId === loanId)
  
  if (loan) {
    selectedLoan.value = loan
    detailDialogVisible.value = true
  } else {
    ElMessage.warning('未找到该贷款信息')
  }
}

// 工具函数
function formatMoney(amount) {
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

function calculateMonthlyPayment(loan) {
  // 简单的等额本息计算（实际业务中需要考虑利率等因素）
  return loan.amount / loan.term
}

function calculateRepaymentProgress(loan) {
  if (!loan.term) return 0
  const paidCount = repaymentSchedule.value.filter(item => item.status === 'PAID').length
  return Math.round((paidCount / loan.term) * 100)
}

function percentageFormat(percentage) {
  return `${percentage}%`
}

function getStatusType(status) {
  const statusMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'REPAYING': 'primary',
    'PAID': 'info'
  }
  return statusMap[status] || 'info'
}

function getStatusText(status) {
  const statusMap = {
    'PENDING': '待审核',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'REPAYING': '还款中',
    'PAID': '已还清'
  }
  return statusMap[status] || status
}

function getRepaymentStatusType(status) {
  return status === 'PAID' ? 'success' : 'warning'
}

function getRepaymentStatusText(status) {
  return status === 'PAID' ? '已还款' : '待还款'
}

function isCurrentInstallment(installment) {
  if (!selectedLoan.value) return false
  return installment.installment === (selectedLoan.value.paidInstallments || 0) + 1
}

// 日期格式化
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
section {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
  padding: 20px;
}

.box {
  width: 100%;
  max-width: 900px;
  margin: 20px auto;
}

.container {
  position: relative;
  padding: 30px;
  width: 100%;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  box-shadow: 0 25px 45px rgba(0, 0, 0, 0.2);
}

.page-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
}

.loan-form {
  max-width: 600px;
  margin: 0 auto 40px;
}

.full-width {
  width: 100%;
}

.loan-list {
  margin-top: 20px;
}

.loan-list h3 {
  margin-bottom: 20px;
  color: #333;
}

.loan-detail {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  width: 100px;
  color: #666;
}

.repayment-form {
  padding: 20px;
}

.loan-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item .label {
  width: 100px;
  color: #666;
  font-size: 14px;
}

.repayment-input {
  margin-top: 20px;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .container {
    padding: 20px;
  }
  
  .box {
    margin: 10px;
  }
  
  .loan-form {
    padding: 0;
  }
  
  .plan-summary {
    grid-template-columns: 1fr;
  }
}
</style>